import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/model/user/self_detail_model.dart';
import 'package:flutter_changdian_football/pages/mine/personal_info/personal_info_controller.dart';
import 'package:flutter_changdian_football/utils/custom_logger.dart';
import 'package:flutter_changdian_football/widget/dialog/club_avatar_dialog.dart';
import 'package:flutter_changdian_football/widget/dialog/input_dialog.dart';
import 'package:flutter_changdian_football/widget/screenutil/custom_screenutil.dart';
import 'package:flutter_changdian_football/widget/sheet/address_picker.dart';
import 'package:flutter_changdian_football/widget/sheet/param_picker.dart';
import 'package:flutter_changdian_football/widget/sheet/select_date_time_picker.dart';
import 'package:flutter_changdian_football/widget/sheet/specialized_position.dart';
import 'package:flutter_pickers/address_picker/locations_data.dart';
import 'package:get/get.dart';

/// 个人信息
class PersonalInfoPage extends StatelessWidget {
  const PersonalInfoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xffF8FAF9),
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: const Color(0xffF8FAF9),
        elevation: 0,
        title: Text(
          '个人信息',
          style: TextStyle(fontSize: 16.sp, color: const Color(0xff333333)),
        ),
        iconTheme: const IconThemeData(
          color: Color(0xff333333)
        ),
      ),
      body: GetBuilder<PersonalInfoController>(
        init: PersonalInfoController(),
        builder: (personalInfoController) {
          return SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 17.w),
            child: Column(
              children: [
                SizedBox(height: 20.w,),

                Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12.r)
                  ),
                  child: Column(
                    children: [
                      _listTileWidget(
                        leftText: '头像',
                        isAvatar: true,
                        avatar: personalInfoController.selfDetailModel?.imageUrl,
                        onTap: () {
                          ClubAvatarDialog.show(
                            Get.context!,
                            title: '选择方式',
                            isRecommend: false,
                            phoneTap: () {
                              personalInfoController.photoSelectImage();
                            },
                            shootTap: () {
                              personalInfoController.shootSelectImage();
                            }
                          );
                        }
                      ),

                      Container(
                        width: double.infinity,
                        height: 0.5.w,
                        color: const Color(0xffE5E5E5),
                      ),

                      _listTileWidget(leftText: '昵称', rightText: personalInfoController.selfDetailModel?.nickname ?? '', onTap: () {
                        personalInfoController.nickNameController.text = personalInfoController.selfDetailModel?.nickname ?? '';
                        InputDialog.show(
                          Get.context!,
                          title: "昵称",
                          hintText: '请输入您的姓名',
                          cancelTap: () {
                            Get.back();
                          },
                          confirmTap: () {
                            personalInfoController.changeNickName();
                          },
                          controller: personalInfoController.nickNameController
                        );
                      }),

                      Container(
                        width: double.infinity,
                        height: 0.5.w,
                        color: const Color(0xffE5E5E5),
                      ),

                      _listTileWidget(leftText: '年龄', rightText: personalInfoController.selfDetailModel?.age ?? '', isRight: false),

                      Container(
                        width: double.infinity,
                        height: 0.5.w,
                        color: const Color(0xffE5E5E5),
                      ),

                      _listTileWidget(leftText: '性别', rightText: 
                        personalInfoController.selfDetailModel?.sex ?? '未知', onTap: () {
                        ParamPicker.show(
                          '选择性别', 
                          Get.context, 
                          [
                            '男',
                            '女',
                          ],
                          selecteds: personalInfoController.selfDetailModel?.sex == '女' ? 1 : 0,
                          onConfirm: (v) {
                            personalInfoController.changeSex(v);
                          }
                        );
                      }),

                      Container(
                        width: double.infinity,
                        height: 0.5.w,
                        color: const Color(0xffE5E5E5),
                      ),

                      _listTileWidget(leftText: '身高', rightText: personalInfoController.selfDetailModel?.height ?? '0cm', onTap: () {
                        List<Map<String, List<String>>> selectHeight = [];
                        int selecteds = 0;

                        int s = 0;
                        for (int i = 140; i <= 230; i++) {
                          selectHeight.add({
                            '$i' : ['cm']
                          });

                          s ++ ;
                          if (int.tryParse('${personalInfoController.selfDetailModel?.height?.replaceAll('cm', '') ?? 0}') == i) {
                            selecteds = s - 1;
                          }
                        } 

                        ParamPicker.showDw(
                          '选择身高', 
                          Get.context, 
                          selectHeight,
                          selecteds: personalInfoController.selfDetailModel?.height == '未知' ? 30 : selecteds,
                          onConfirm: (v) {
                            personalInfoController.changeHeight(v, selectHeight[v].keys.first);
                          }
                        );
                      }),

                      Container(
                        width: double.infinity,
                        height: 0.5.w,
                        color: const Color(0xffE5E5E5),
                      ),

                      _listTileWidget(leftText: '体重', rightText: personalInfoController.selfDetailModel?.weight ?? '0kg', onTap: () {
                        // List<String> selectHeight = [];
                        // int selecteds = 0;
                        // for (int i = 40; i <= 150; i++) {
                        //   selectHeight.add('$i');
                        //   if (int.tryParse('${personalInfoController.selfDetailModel?.weight?.replaceAll('cm', '') ?? 0}') == i) {
                        //     selecteds = i;
                        //   }
                        // } 
                        // ParamPicker.show(
                        //   '选择体重', Get.context, selectHeight,
                        //   selecteds: personalInfoController.selfDetailModel?.weight == '未知' ? 0 : selecteds,
                        //   onConfirm: (v) {
                        //     personalInfoController.changeWdight(v, selectHeight[v]);
                        //   }
                        // );
                        List<Map<String, List<String>>> selectHeight = [];
                        int selecteds = 0;

                        int s = 0;
                        for (int i = 40; i <= 150; i++) {
                          selectHeight.add({
                            '$i' : ['kg']
                          });

                          s ++ ;
                          if (int.tryParse('${personalInfoController.selfDetailModel?.weight?.replaceAll('kg', '') ?? 0}') == i) {
                            selecteds = s - 1;
                          }
                        } 

                        ParamPicker.showDw(
                          '选择体重', 
                          Get.context, 
                          selectHeight,
                          selecteds: personalInfoController.selfDetailModel?.weight == '未知' ? 20 : selecteds,
                          onConfirm: (v) {
                            personalInfoController.changeWdight(v, selectHeight[v].keys.first);
                          }
                        );
                      }),
                    ],
                  ),
                ),


                SizedBox(height: 20.w,),


                Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12.r)
                  ),
                  child: Column(
                    children: [
                      _listTileWidget(leftText: '生日', rightText: personalInfoController.selfDetailModel?.birthday ?? '未知', onTap: () {
                        SelectDateTimePicker.show(
                          '选择生日', context, personalInfoController.selfDetailModel?.birthday == '未知' ? DateTime.now().toString() : personalInfoController.selfDetailModel?.birthday ?? DateTime.now().toString(),
                          onConfirm: (v) {
                            personalInfoController.changeBirthday(v);
                          }
                        );
                      }),

                      Container(
                        width: double.infinity,
                        height: 0.5.w,
                        color: const Color(0xffE5E5E5),
                      ),

                      _listTileWidget(leftText: '地区', rightText: '${personalInfoController.selfDetailModel?.provinceName ?? ''} ${personalInfoController.selfDetailModel?.cityName ?? ''}', onTap: () {
                        AddressPicker.show(
                          context,
                          initProvince: personalInfoController.selfDetailModel?.provinceName ?? '',
                          initCity: personalInfoController.selfDetailModel?.cityName ?? '',
                          onConfirm: (province, city, district) {
                            List<String> codeList = Address.getCityCodeByName(provinceName: province, cityName: city, townName: district);
                            personalInfoController.selfDetailModel?.provinceCode = codeList[0];
                            personalInfoController.selfDetailModel?.provinceName = province;
                            personalInfoController.selfDetailModel?.cityCode = codeList[1];
                            personalInfoController.selfDetailModel?.cityName = city;
                            personalInfoController.update();
                          }
                        );
                      }),
                    ],
                  ),
                ),




                SizedBox(height: 20.w,),


                Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12.r)
                  ),
                  child: Column(
                    children: [
                      _listTileWidget(
                        leftText: '擅长位置', 
                        rightText: personalInfoController.goodPositionCode.join(','),
                        onTap: () {
                          List<Position> positionList = [];
                          for (int i = 0; i < personalInfoController.goodPositionCode.length; i++) {
                            positionList.add(
                              Position(
                                personalInfoController.selfDetailModel?.goodPosition?[i].subdivisionPosition ?? '', 
                                personalInfoController.selfDetailModel?.goodPosition?[i].subdivisionPositionCode ?? '', true)
                            );
                          }

                          // Position('name', 'code', false)/

                          SpecializedPosition.show(
                            '擅长位置', context,
                            selectedPosition: positionList,
                            onConfirm: (v) {
                              Get.back();
                              personalInfoController.goodPositionCode.clear();
                              personalInfoController.selfDetailModel?.goodPosition?.clear();

                              for (int i = 0; i < positionList.length; i++) {
                                personalInfoController.goodPositionCode.add(positionList[i].name);
                                personalInfoController.selfDetailModel?.goodPosition?.add(
                                  GoodPosition.fromJson({
                                    'subdivisionPosition': positionList[i].name,
                                    'subdivisionPositionCode': positionList[i].code,
                                  })
                                );
                              }
                              personalInfoController.update();
                            }
                          );
                        }
                      ),
                    ],
                  ),
                ),

                SizedBox(height: 20.w,),

                GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    personalInfoController.comfirmUpdate();
                  },
                  child: Container(
                    width: double.infinity,
                    alignment: Alignment.center,
                    padding: EdgeInsets.symmetric(vertical: 12.w),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12.r),
                      color: Colors.white
                    ),
                    child: Text('确认修改', style: TextStyle(fontSize: 15.sp, color: const Color(0xff499360)),),
                  ),
                )
              ],
            ),
          );
        }
      ),
    );
  }

  _listTileWidget({
    String leftText = '',
    String rightText = '',
    bool isRight = true,
    bool isAvatar = false,
    String? avatar,
    Function? onTap
  }) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        onTap?.call();
      },
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 12.w),
        child: Row(
          children: [
            SizedBox(
              child: Text(leftText, style: TextStyle(fontSize: 15.sp, color: const Color(0xff323232)),),
            ),
    
            const Spacer(),
    
            if (isAvatar == true) ...[
              Container(
                width: 44.w,
                height: 44.w,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(44.r),
                ),
                child: avatar == null ? ClipRRect(
                  borderRadius: BorderRadius.circular(44.r),
                  child: Image.asset('assets/images/logo_gr.png', fit: BoxFit.fill,),
                ) : ClipRRect(
                  borderRadius: BorderRadius.circular(44.r),
                  child: Image.network(avatar, fit: BoxFit.fill,),
                ),
              )
            ] else ...[
              SizedBox(
                child: Text(rightText, style: TextStyle(fontSize: 14.sp, color: const Color(0xff999999)),),
              ),
            ],
    
            if (isRight) ...[
              SizedBox(width: 8.w,),
    
              SizedBox(
                width: 10.w,
                height: 10.w,
                child: Image.asset('assets/images/icon_arrow_grey_right.png'),
              )
            ],
          ],
        ),
      ),
    );
  }

}


